package com.kelab.dify.example;

import com.kelab.dify.DifyClient;
import com.kelab.dify.config.DifyConfig;
import com.kelab.dify.exception.DifyException;
import com.kelab.dify.model.chat.ChatRequest;
import com.kelab.dify.model.chat.ChatResponse;
import com.kelab.dify.model.workflow.WorkflowRequest;
import com.kelab.dify.model.workflow.WorkflowResponse;
import com.kelab.dify.service.AudioService;
import com.kelab.dify.service.FileService;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * Dify客户端使用示例
 * 展示如何使用各种API功能
 * 
 * @author kelab
 * @version 1.0
 */
public class DifyClientExample {
    
    private static final String API_KEY = "your-api-key-here";
    private static final String USER_ID = "user-123";
    
    public static void main(String[] args) {
        // 创建配置
        DifyConfig config = DifyConfig.builder(API_KEY)
                .baseUrl("https://api.dify.ai/v1")
                .connectTimeout(30000)
                .readTimeout(60000)
                .enableLogging(true)
                .build();
        
        // 创建客户端
        DifyClient client = new DifyClient(config);
        
        try {
            // 示例1: 聊天对话
            chatExample(client);
            
            // 示例2: 流式聊天
            streamChatExample(client);
            
            // 示例3: 工作流执行
            workflowExample(client);
            
            // 示例4: 文件上传
            fileUploadExample(client);
            
            // 示例5: 音频处理
            audioExample(client);
            
            // 示例6: 知识库操作
            knowledgeBaseExample(client);
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭客户端
            client.close();
        }
    }
    
    /**
     * 聊天对话示例
     */
    private static void chatExample(DifyClient client) throws DifyException {
        System.out.println("=== 聊天对话示例 ===");
        
        // 创建聊天请求
        ChatRequest request = new ChatRequest("你好，请介绍一下自己", USER_ID);
        
        // 发送消息
        ChatResponse response = client.chat().sendMessage(request);
        
        System.out.println("用户: " + request.getQuery());
        System.out.println("AI: " + response.getAnswer());
        System.out.println("对话ID: " + response.getConversationId());
        System.out.println();
    }
    
    /**
     * 流式聊天示例
     */
    private static void streamChatExample(DifyClient client) throws DifyException {
        System.out.println("=== 流式聊天示例 ===");
        
        ChatRequest request = new ChatRequest("请详细解释什么是人工智能", USER_ID);
        
        System.out.println("用户: " + request.getQuery());
        System.out.print("AI: ");
        
        // 发送流式消息
        CompletableFuture<Void> future = client.chat().sendMessageStream(
                request,
                response -> {
                    // 处理每个流式响应
                    if ("message".equals(response.getEvent()) && response.getAnswer() != null) {
                        System.out.print(response.getAnswer());
                    }
                },
                error -> {
                    System.err.println("流式聊天错误: " + error.getMessage());
                }
        );
        
        try {
            // 等待流式响应完成
            future.get();
            System.out.println();
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 工作流执行示例
     */
    private static void workflowExample(DifyClient client) throws DifyException {
        System.out.println("=== 工作流执行示例 ===");
        
        // 创建工作流输入参数
        Map<String, Object> inputs = new HashMap<>();
        inputs.put("query", "分析一下当前的市场趋势");
        inputs.put("language", "中文");
        
        WorkflowRequest request = new WorkflowRequest(inputs, USER_ID);
        
        // 执行工作流
        WorkflowResponse response = client.workflow().runWorkflow(request);
        
        System.out.println("工作流执行结果:");
        System.out.println("任务ID: " + response.getTaskId());
        System.out.println("工作流运行ID: " + response.getWorkflowRunId());
        System.out.println();
    }
    
    /**
     * 文件上传示例
     */
    private static void fileUploadExample(DifyClient client) throws DifyException {
        System.out.println("=== 文件上传示例 ===");
        
        // 创建一个示例文件（实际使用时替换为真实文件）
        String content = "这是一个测试文档的内容。";
        byte[] fileData = content.getBytes();
        
        // 上传文件
        FileService.FileUploadResponse response = client.file().uploadFile(fileData, "test.txt", USER_ID);
        
        System.out.println("文件上传成功:");
        System.out.println("文件ID: " + response.getId());
        System.out.println("文件名: " + response.getName());
        System.out.println("文件大小: " + response.getSize());
        System.out.println();
    }
    
    /**
     * 音频处理示例
     */
    private static void audioExample(DifyClient client) throws DifyException {
        System.out.println("=== 音频处理示例 ===");
        
        // 文本转语音
        AudioService.AudioResponse audioResponse = client.audio().textToAudio(
                "你好，这是一个文本转语音的测试", 
                USER_ID, 
                null, 
                false
        );
        
        System.out.println("文本转语音成功:");
        System.out.println("任务ID: " + audioResponse.getTaskId());
        System.out.println("音频格式: " + audioResponse.getFormat());
        
        // 注意：实际的语音转文本需要真实的音频文件
        // AudioService.TextResponse textResponse = client.audio().audioToText(audioFile, USER_ID);
        
        System.out.println();
    }
    
    /**
     * 知识库操作示例
     */
    private static void knowledgeBaseExample(DifyClient client) throws DifyException {
        System.out.println("=== 知识库操作示例 ===");
        
        // 获取数据集列表
        try {
            client.knowledgeBase().getDatasets(1, 10);
            System.out.println("成功获取数据集列表");
        } catch (DifyException e) {
            System.out.println("获取数据集列表失败: " + e.getMessage());
        }
        
        // 创建数据集
        try {
            client.knowledgeBase().createDataset("测试数据集", "这是一个测试数据集");
            System.out.println("成功创建数据集");
        } catch (DifyException e) {
            System.out.println("创建数据集失败: " + e.getMessage());
        }
        
        System.out.println();
    }
}